// 返回结果格式化处理
import { QI_NIU_YUN_URL } from '../config/index'
import { BASE_URL as baseUrl } from '../config'
import { getHeight } from './sevice'
import weibo from './weibo-emotions'

const genders = ['未知', '男', '女']
const imgUrl = baseUrl + '/public/images'
const emotions = weibo.emotions
const weibo_icon_url = weibo.weibo_icon_url

export function parseTopic(items: []) {
  const newItems = items.map((item) => {
    // item.hasFollow = false
    item.iconPath = QI_NIU_YUN_URL + item.iconPath
    return item
  })
  return newItems
}

export function parsePost(items: []) {
  const newItems = items.map((post) => {
    if (post.user) {
      post.user.gender = parseGender(post.user.gender)
    }
    post.origTxt = post.content
    post.content = parseEmoji(post.content)
    if (post.imgs.length) {
      post.height = getHeight()
      post.imgs = parseImgs(post.imgs)
    }
    return post
  })
  return newItems
}

export function parseGender(gender) {
  return genders[gender]
}

export const weibo_emojis = (function() {
  const _emojis = {}
  for (const key in emotions) {
    if (emotions.hasOwnProperty(key)) {
      const ele = emotions[key]
      for (const item of ele) {
        _emojis[item.value] = {
          id: item.id,
          value: item.value,
          icon: item.icon.replace('/', '_'),
          url: weibo_icon_url + item.icon
        }
      }
    }
  }
  return _emojis
})()

export function parseEmoji(txt) {
  if (!txt) {
    return ''
  }
  return txt
    .split(/(\[[\u4e00-\u9fff,\uff1f,\w]{1,8}\])/)
    .filter((str) => str.length > 0)
    .map((str) => {
      let obj = {}
      if (/\[([\u4e00-\u9fff,\uff1f,\w]{1,8})\]/.test(str)) {
        if (weibo_emojis[str]) {
          obj.type = 1
          obj.src = weibo_emojis[str].url
        } else {
          obj.type = 0
          obj.value = str
        }
      } else {
        obj.type = 0
        obj.value = str
      }
      return obj
    })
}

export function parseImgs(imgs) {
  return imgs.map((img) => {
    if (img.isQiniu) {
      const path = img.path
      img.fileName = img.path
      img.path = QI_NIU_YUN_URL + 'thumb_' + path
      img.origPath = QI_NIU_YUN_URL + path
    } else {
      img.path = imgUrl + img.path
      img.origPath = imgUrl + img.origPath
    }
    return img
  })
}
